import settings
from datetime import datetime, timedelta
import httpx
from .apis import DingAPI
from httpx import Timeout


class DingAccessTokenManager:
    def __init__(self):
        self.app_key = settings.DING_Client_ID
        self.app_secret = settings.DING_Client_Secret
        self._access_token: str | None = None
        self._expire_at: str | None = None

    @property
    def access_token(self) -> str:
        if not self._access_token or self._expire_at is None or self._is_expire_soon:
            url = DingAPI.build_access_token_url()
            data = {
                "appKey": self.app_key,
                "appSecret": self.app_secret
            }
            with httpx.Client(timeout=600) as client:
                response = client.post(url=url, json=data)
                response.raise_for_status()
                result = response.json()
                access_token = result.get('accessToken')
                self._access_token = access_token
                self._expire_at = (datetime.now() + timedelta(hours=2)).timestamp()
        return self._access_token

    @property
    def _is_expire_soon(self):
        if not self._expire_at:
            return True
        gap = settings.DING_ACCESS_TOKEN_REFRESH
        if self._expire_at < datetime.now().timestamp() - gap:
            return True
        return False


